package com.xucia.jsponic.servlet;

import java.io.IOException;
import java.io.Writer;

import org.mozilla.javascript.BaseFunction;
import org.mozilla.javascript.Context;
import org.mozilla.javascript.NativeObject;
import org.mozilla.javascript.Scriptable;
import org.mozilla.javascript.Undefined;
/**
 * This class allows scripts to be executed and write to the document output
 * @author Kris Zyp
 *
 */
public class Document extends NativeObject {
	public static ThreadLocal<Writer> writer = new ThreadLocal<Writer>();
	public Document() {
		super();
		put("write", this, new BaseFunction() {
			@Override
			public Object call(Context cx, Scriptable scope,
					Scriptable thisObj, Object[] args) {
				try {
					writer.get().write(args.length > 0 ? (String) args[0] : "");
				} catch (IOException e) {
					e.printStackTrace();
				}
				return Undefined.instance;
			}
			
		});
		put("writeln", this, new BaseFunction() {
			@Override
			public Object call(Context cx, Scriptable scope,
					Scriptable thisObj, Object[] args) {
				try {
					writer.get().write((args.length > 0 ? args[0] : "") + "\n");
				} catch (IOException e) {
					e.printStackTrace();
				}
				return Undefined.instance;				
			}
			
		});
		put("open", this, new BaseFunction() {
			@Override
			public Object call(Context cx, Scriptable scope,
					Scriptable thisObj, Object[] args) {
				// does this have any use?
				return Undefined.instance;
			}
			
		});
		put("close", this, new BaseFunction() {
			@Override
			public Object call(Context cx, Scriptable scope,
					Scriptable thisObj, Object[] args) {
				// does this have any use?
				return Undefined.instance;
			}
			
		});

	}
	@Override
	public String getClassName() {
		return "HTMLDocument";
	}
	

}
